import { createRouter, createWebHashHistory, RouteLocationNormalized, NavigationGuardNext } from 'vue-router'
import routes from './routes'
import store from '/@/store'
import { getToken } from '/@/utils/auth'
import { handleBreadcrumb, setPageTitle } from '/@/utils/index'

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  strict: true,
  routes,
})

const whiteList = ['/login']

router.beforeEach((
  to: RouteLocationNormalized,
  _from: RouteLocationNormalized,
  next: NavigationGuardNext
) => {
  if (getToken()) {
    let _path = to.fullPath
    if (_path !== '/dashboard') {
      store.commit('tabsView/ADD_TAB', {
        title: to.meta.title,
        path: _path
      })
    } else {
      _path = '/'
    }

    store.commit('tabsView/SET_ACTICVE_KEY', _path)
    store.commit('tabsView/SET_OPEN_KEYS', to.matched.map(item => item.path))
    store.commit('app/SET_BREADCRUMB', handleBreadcrumb(to))
    store.dispatch('user/getUserInfo')
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach((to: RouteLocationNormalized) => {
  setPageTitle(to)
})

export default router
